<template>
  <div class="app-container">
    <el-form label-width="120px">
      <el-form-item label="问题标题">
        <el-input v-model="question.title"/>
      </el-form-item>
      <el-form-item label="问题内容">
        <tinymce :height="300" v-model="question.content"  />
      </el-form-item>
      <el-form-item>
        <el-button :disabled="saveBtnDisabled" type="primary" @click="saveOrUpdate">提交</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import questionApi from "../../api/qa/question";
import {mapGetters} from "vuex"
import Tinymce from '@/components/Tinymce'
export default {
  components:{Tinymce},
name: "addQuestion",
  data(){
  return {
    question:{},
    saveBtnDisabled:false
  }
  },
  computed:{
  ...mapGetters(['name','avatar'])
  },
  created() {
      this.init();
  },
  watch: {
    $route(to, from) {
      this.init()
    }
  },
  methods:{
    init(){
      if(this.$route.params&&this.$route.params.id) {
        this.question.id = this.$route.params.id;
        this.getQuestion();
      }
      else
        this.question={};
    },
    getQuestion(){
      questionApi.getQuestionById(this.question.id)
        .then(response => {
          this.question = response.data.info;
        });
    },
    saveOrUpdate(){
      this.question.userName=this.name;
      this.question.userAvatar=this.avatar;
      if(this.$route.params&&this.$route.params.id)
      {
        this.updateQuestion();
      }
      else
        this.saveQuestion();
    },
    saveQuestion(){
      questionApi.addQuestion(this.question)
        .then(response => {
          this.$message({
            type: 'success',
            message: '添加成功!'
          })
          //回到列表界面
          this.$router.push({ path: '/qa/list' })
        })
    },
    updateQuestion(){
      questionApi.updateQuestion(this.question)
        .then(response => {
          this.$message({
            type: 'success',
            message: '更新成功!'
          })
          //回到列表界面
          this.$router.push({ path: '/qa/list' })
        })
    }
  }
}
</script>

<style scoped>
.tinymce-container {
  line-height: 29px;
}
</style>
